// 模拟第三方美的api，生成美的设备状态数据并提供设备控制方法
import {getBrandConfig} from "../../brand/getBrandConfig";
import axios from "axios";
import {MockThirdParty} from "../MockThirdParty";
import {AppDataSource} from "../../config/database";
import { AccessToken } from '../../entity/Accesstoken';
import { MideaNotifyBody } from '../../api/notify.route';
import { Device } from "../../entity/Device";
import { In } from "typeorm/find-options/operator/In";
import { MockThirdPartyXiaomi } from "./MockThirdPartyXiaomi";
 import * as crypto from 'crypto';


export class MockThirdPartyMidea extends MockThirdParty {
  private deviceGroups: Map<string, string[]> = new Map(); // 存储分组设备关系

  constructor() {
    // 初始化模拟第三方服务
    const config = getBrandConfig('midea');
    super(config.app_id, config.app_secret);
  }

  // 生成传感器模拟数据
  public generateMideaDeviceData(deviceId: string): Record<string, any> {
    const now = new Date();
    const deviceType = deviceId.split('_')[1];

    switch (deviceType) {

        // 空调
      case 'midea_ac':
        return {
          online: Math.random() > 0.1, // 90%在线率
          target_temperature: this.getRandomFloat(16, 30, 1),
          fan_speed: ['low', 'medium', 'high', 'auto'][this.getRandomInt(0, 3)],
          mode: ['cool', 'heat', 'dry', 'fan'][this.getRandomInt(0, 3)],
          power: Math.random() > 0.5 ? 'ON' : 'OFF'
        };

        // 加湿器
      case 'midea_humidifier':
        const power = this.getRandomInt(0, 1);
        return {
          online: Math.random() > 0.1,
          power: power ? 1 : 0,
          status: power ?
              ['running', 'paused'][this.getRandomInt(0, 1)] : 'off',
          mode: ['auto', 'sleep', 'strong'][this.getRandomInt(0, 2)],
          target_humidity: this.getRandomInt(30, 80)
        };

        // 除湿器
      case 'midea_dehumidifier':
        return {
          online: Math.random() > 0.1,
          power: this.getRandomInt(0, 1) ? 1 : 0,
          status: this.getRandomInt(0, 1) ?
              ['running', 'paused'][this.getRandomInt(0, 1)] : 'off',
          mode: ['auto', 'sleep', 'dry'][this.getRandomInt(0, 2)],
          target_humidity: this.getRandomInt(30, 80)
        };

        // 空气净化器
      case 'midea_air_purifier':
        return {
          online: Math.random() > 0.1,
          power: this.getRandomInt(0, 1) ? 1 : 0,
          status: this.getRandomInt(0, 1) ?
              ['running', 'paused'][this.getRandomInt(0, 1)] : 'off',
          mode: ['auto', 'silent', 'strong'][this.getRandomInt(0, 2)],
          fan_level: this.getRandomInt(1, 3), // 1-3级风速
        };

        // 默认返回基础状态
      default:
        return {
          online: Math.random() > 0.1,
          power: Math.random() > 0.5 ? 'ON' : 'OFF',
          time: now.toISOString()
        };
    }
  }

  //美的设备状态推送方法
  async pushMideaDeviceStatus(
      deviceId: string,
      userId: string,
      properties: Record<string, any>
  ): Promise<void> {
    const notifyUrl = 'http://localhost:3000/api/midea/notify';

    try {
      // 严格匹配服务端接口的MideaNotifyBody格式
      const requestBody: MideaNotifyBody = {
        applianceCode: deviceId,
        properties
      };

      const response = await axios.post(notifyUrl, requestBody);

      if (response.data.code !== 200) {
        throw new Error(`推送失败: ${response.data.message}`);
      }

      console.log(`[Midea] 设备 ${deviceId} 状态推送至服务端成功`, properties);
    } catch (err) {
      if (err instanceof Error) {
        console.error(`[Midea] 状态推送至服务端失败:`, err.message);
      } else {
        console.error(`[Midea] 状态推送至服务端失败:`, err);
      }
      throw new Error('推送至服务端服务不可用');
    }
  }

  // 初始化分组关系
  async initDeviceGroups(userId: string) {
    const deviceRepo = AppDataSource.getRepository(Device);
    const devices = await deviceRepo.find({where: {userId}});

    // 按分组ID组织设备
    const groupMap = new Map<string, string[]>();
    devices.forEach(device => {
      if (device.gid) {
        if (!groupMap.has(device.gid)) {
          groupMap.set(device.gid, []);
        }
        groupMap.get(device.gid)!.push(device.did);
      }
    });

    this.deviceGroups = groupMap;
  }

  // 获取同组设备
  private getGroupDevices(deviceId: string): string[] {
    // 默认组包含所有设备
    let groupDevices: string[] = [];

    // 查找设备所在分组
    for (const [gid, devices] of this.deviceGroups) {
      if (devices.includes(deviceId)) {
        groupDevices = devices;
        break;
      }
    }

    return groupDevices.length > 0 ? groupDevices : [...this.deviceGroups.values()].flat();
  }

  // 美的设备控制方法
  async controlDevice(
      accessToken: string,
      reqId: string,
      applianceId: string,
      control: { operation: string; value: any }
  ): Promise<{
    reqId: string;
    status: { operation: string; status: any; result: number };
  }> {
    // 验证access_token
    const tokenRepo = AppDataSource.getRepository(AccessToken);
    const tokenRecord = await tokenRepo.findOne({
      where: {token: accessToken, appId: this.appId}
    });

    if (!tokenRecord || tokenRecord.expiresAt < new Date()) {
      throw new Error('1006 用户验证失败');
    }

    // 获取设备信息
    const deviceRepo = AppDataSource.getRepository(Device);
    const device = await deviceRepo.findOne({
      where: {did: applianceId, userId: tokenRecord.userId}
    });

    if (!device) {
      throw new Error('1300 设备不存在');
    }

    // 获取同组设备
    const groupDevices = this.getGroupDevices(applianceId);

    // 查找同组的传感器设备
    const xiaomiDeviceRepo = AppDataSource.getRepository(Device);
    const sensors = await xiaomiDeviceRepo.find({
      where: {
        did: In(groupDevices),
        type: In(['mi_temp_hum_sensor', 'mi_air_sensor']),
        brand: 'xiaomi' // 只影响小米传感器
      }
    });

    // 处理空调温度控制
    if ((device.type.includes('ac') && control.operation === 'target_temperature') ||
        (device.type.includes('humidifier') && control.operation === 'target_humidity')) {
      sensors.forEach(sensor => {
        const xiaomiService = new MockThirdPartyXiaomi();
        const lockType = device.type.includes('ac') ? 'temperature' : 'humidity';
        xiaomiService.lockSensorValue(sensor.did, lockType, control.value);
      });
    }
    // 设备关闭时解除锁定
    else if (control.operation === 'power' && control.value === 'OFF') {
      const xiaomiService = new MockThirdPartyXiaomi();
      sensors.forEach(sensor => {
        xiaomiService.lockSensorValue(sensor.did, 'temperature', null);
      });
    }

    // 推送状态变更（格式转换）
    await this.pushMideaDeviceStatus(applianceId, tokenRecord.userId, {
      [control.operation]: control.value
    });

    return {
      reqId,
      status: {
        operation: control.operation,
        status: control.value,
        result: 1 // 总是返回成功
      }
    };
  }


  // 辅助方法
  private getRandomInt(min: number, max: number): number {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  private getRandomFloat(min: number, max: number, decimals: number): number {
    const value = Math.random() * (max - min) + min;
    return parseFloat(value.toFixed(decimals));
  }

}
